package pl.edu.szlif.mosm.j2melib;

import java.util.Enumeration;
import java.util.Hashtable;

/**
 * Basic Tile Cache implementation - with hashtable addressed by strings
 * and "random" tiles deleting if number of cached tiles is beyond max.
 * 
 * @author Adam Morawski
 */
public class BasicTileCache implements TileCache {
	protected Hashtable ht;
	protected int maxSize;

	public BasicTileCache(int cacheSize) {
		ht = new Hashtable();
		maxSize = cacheSize;
	}
	
	public boolean contains(int x, int y, int z) {
		String k = x+"."+y+"."+z;
		return ht.containsKey(k);
	}

	public Object get(int x, int y, int z) {
		String k = x+"."+y+"."+z;
		return ht.get(k);
	}

	public void put(int x, int y, int z, Object tile) {
		String k = x+"."+y+"."+z;
		ht.put(k, tile);
		if(ht.size() > maxSize)
			reorganize();
	}
	
	protected void reorganize() {
		// subclasses can implement smarter reorganization
	     for (Enumeration e = ht.keys() ; ht.size() > maxSize/2 ;)
	         ht.remove(e.nextElement());
	}
}
